package com.eqs.enterprisequestionnaire.service.Impl;

import com.eqs.enterprisequestionnaire.mapper.AnswerMapper;
import com.eqs.enterprisequestionnaire.model.pojo.Answer;
import com.eqs.enterprisequestionnaire.model.pojo.Option;
import com.eqs.enterprisequestionnaire.model.pojo.Question;
import com.eqs.enterprisequestionnaire.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.isSortType;

@Service
public class SortQuestionImpl implements SortQuestionService {
    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private OptionService optionService;

    @Autowired
    private HistoryService historyService;

    @Override
    public Integer getOptionOrder(Integer optionId) {
        // 获取选项对应的问题
        Question question = historyService.getQuestionByOptionId(optionId);

        // 判断问题类型是否为排序题
        if (!isSortType(question.getType())) {
            throw new IllegalArgumentException("Question is not of a sort type.");
        }

        // 获取该问题的所有选项
        List<Option> options = historyService.getListOptionByQuestionId(question.getQuestionId());

        // 获取该问题的所有答案
        List<Answer> answers = historyService.getListAnswerByQuestionId(question.getQuestionId());

        Answer selectedAnswer = historyService.getAnswerByOptionId(optionId);
        if (selectedAnswer != null) {
            // 获取当前最大排序值
            int maxOrder = answers.stream().mapToInt(Answer::getSort).max().orElse(0);

            // 如果当前最大排序值为 -1，则表示所有答案的排序值都未设置，初始化排序值为1
            if (maxOrder == -1) {
                maxOrder = 0;
            }

            // 更新选项对应的答案对象的排序
            selectedAnswer.setSort(maxOrder + 1);
            answerService.updateById(selectedAnswer);

            // 更新其他未设置排序的答案对象的排序为 -1
            for (Answer answer : answers) {
                if (answer.getSort() == -1 && !answer.getId().equals(selectedAnswer.getId())) {
                    answer.setSort(-1);
                    answerService.updateById(answer);
                }
            }

            return selectedAnswer.getSort();
        } else {
            throw new IllegalArgumentException("Option not found or not associated with the question.");
        }
    }
}